from datetime import datetime
from decimal import Decimal

from django.db import transaction
from django_redis import get_redis_connection
from rest_framework import serializers

from goods.models import SKU
from orders.models import OrderInfo, OrderGoods


class OrderSKUSerializer(serializers.ModelSerializer):
    """订单结算商品序列化器类"""
    count = serializers.IntegerField(label='结算商品数量')

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'count')


class OrderSerializer(serializers.ModelSerializer):
    """订单创建序列化器类"""

    class Meta:
        model = OrderInfo
        fields = ('order_id', 'address', 'pay_method')
        extra_kwargs = {
            'order_id': {  # 订单编号
                'read_only': True,
            },
            'address': {
                'write_only': True
            },
            'pay_method': {
                'write_only': True,
                'required': True
            }

        }

    def create(self, validated_data):
        """保存订单数据"""
        # 获取address和pay_method
        address = validated_data['address']
        pay_method = validated_data['pay_method']

        # 获取登录用户的user
        user = self.context['request'].user
        # 获取订单编号：年月日时分秒 + 用户id
        order_id = datetime.now().strftime('%Y%m%d%H%M%S') + '%010d' % user.id
        # 订单商品总数量和实付款
        total_count = 0
        total_amount = 0
        # 订单运费
        freight = Decimal(10.0)
        # 支付状态
        # if pay_method == OrderInfo.PAY_METHODS_ENUM['CASH']:  # 货到付款
        #     status = OrderInfo.ORDER_STATUS_ENUM['UNSEND']
        # else: # 在线支付
        #     status = OrderInfo.ORDER_STATUS_ENUM['UNPAID']

        status = OrderInfo.ORDER_STATUS_ENUM['UNSEND'] if pay_method == OrderInfo.PAY_METHODS_ENUM['CASH'] else \
        OrderInfo.ORDER_STATUS_ENUM['UNPAID']
        # 获取redis连接
        redis_conn = get_redis_connection('cart')

        # 从redis set中获取用户购物车被勾选的的商品id
        # 获取键
        cart_selected_key = 'cart_selected_%s' % user.id
        sku_ids = redis_conn.smembers(cart_selected_key)

        # 从redis hash中获取用户购物车记录的商品id及对应的数量count
        # 获取键
        cart_key = 'cart_%s' % user.id
        cart_dict = redis_conn.hgetall(cart_key)

        with transaction.atomic():
            # with语句块下方的代码凡是涉及到数据库的操作 都会放到同一个事务中

            # 设置事务保存点
            sid = transaction.savepoint()

            try:
                # 向订单基本信息表添加一条记录
                order = OrderInfo.objects.create(
                    order_id=order_id,
                    user=user,
                    address=address,
                    total_count=total_count,
                    total_amount=total_amount,
                    freight=freight,
                    pay_method=pay_method,
                    status=status
                )

                # 订单中包含几个商品，就要向订单商品列表中添加几条记录

                for sku_id in sku_ids:
                    # 获取用户的所有的该商品的数量
                    count = cart_dict[sku_id]
                    count = int(count)

                    for i in range(3):
                        # 根据sku_id 获取商品
                        sku = SKU.objects.get(id=sku_id)

                        # 判断商品的库存
                        if count > sku.stock:
                            # 回滚sid保存点
                            transaction.savepoint_rollback(sid)
                            raise serializers.ValidationError('商品库存不足')

                        # 记录一下此时的库存
                        origin_stock = sku.stock
                        new_stock = origin_stock - count
                        new_sales = sku.sales + count

                        # 减少商品库存增加销量
                        # sku.stock -= count
                        # sku.sales += count
                        # sku.save()

                        # 查询
                        res = SKU.objects.filter(id=sku_id, stock=origin_stock).update(stock=new_stock, sales=new_sales)

                        # 做出判断
                        if res == 0:
                            # 说明更新失败，此时原有库存发生变化，此时有多于自己的对象在操作数据库
                            if i == 2:
                                # 说明3次更新失败，此时进行回滚 报下单失败
                                transaction.savepoint_rollback(sid)
                                raise serializers.ValidationError('下单失败2')

                            continue

                        # 向订单中增加一条记录
                        OrderGoods.objects.create(
                            order=order,
                            sku=sku,
                            count=count,
                            price=sku.price
                        )
                        # 累计计算订单商品中的总数和总计付款金额
                        total_count += count
                        total_amount += sku.price * count

                        # 成功更新 跳出循环
                        break

                # 实际付款 并进行保存
                total_amount += freight
                order.total_count = total_count
                order.total_amount = total_amount
                order.save()
            except serializers.ValidationError:
                raise
            except Exception:
                # 回滚到保存点
                transaction.savepoint_rollback(sid)
                raise serializers.ValidationError('下单失败')

        # 3、清除购物车中的记录
        pl = redis_conn.pipeline()
        pl.hdel(cart_key, *sku_ids)
        pl.srem(cart_selected_key, *sku_ids)
        pl.execute()

        # 返回参数
        return order
